﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CRM.Database.Model
{
    public class ConfigurationsCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        //protected static List<Configurations> _list;
        /// <summary>
        /// Список конфигураций
        /// </summary>
        public List<Configurations> ConfigurationsList
        {
            get
            {
                //if (_list == null)
                //    _list = DB.Entities.Configurations.ToList();
                //return _list;
                return Entities.Configurations.ToList();
            }
        }

        /// <summary>
        /// Поиск элемента по идентификатору
        /// </summary>
        /// <param name="id">Идентификатор</param>
        /// <returns>Конфигурация</returns>
        public override object GetItemById(int id)
        {
            return Entities.Configurations.Find(id);
        }

        ///// <summary>
        ///// Обнуление статической коллекции
        ///// </summary>
        //protected override void SetStaticListToNULL()
        //{
        //    _list = null;
        //}

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            throw new NotImplementedException();
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (Configurations);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(ConfigurationsList);
        }

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (Configurations) item;
            if (newObject == null)
                return false;


            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as Configurations;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Comments))
                object4Update.Comments = newObject.Comments;

            if (!string.IsNullOrEmpty(newObject.Name))
                object4Update.Name = newObject.Name;

            if (!string.IsNullOrEmpty(newObject.Value))
                object4Update.Value = newObject.Value;


            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Protected methods

        /// <summary>
        /// получение элемента по имени
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetValueByName(string name)
        {
            Configurations item = ConfigurationsList.FirstOrDefault(c => c.Name == name);
            if (item != null)
                return item.Value;
            return "";
        }

        #endregion

        #region Extended public properties

        #region General

        /// <summary>
        /// Возвращает IP адрес почтового сервера или null
        /// </summary>
        /// <returns></returns>
        public string MailServerIp
        {
            get { return GetValueByName("MailServerIP"); }
        }

        /// <summary>
        /// Возвращает номер порта почтового вервера для отправки писем или 0;
        /// </summary>
        /// <returns></returns>
        public int MailServerPort
        {
            get
            {
                try
                {
                    int port;
                    int.TryParse(GetValueByName("MailServerPort"), out port);
                    return port;
                }
                catch
                {
                    return 0;
                }
            }
        }

        #endregion

        #region Trainings

        /// <summary>
        /// Возвращает адрес отправителя учебного цетнра по умолчанию из настроек или null
        /// </summary>
        /// <returns></returns>
        public string TrainingsDefaultMAILFROMString
        {
            get { return GetValueByName("TCMailFromDefaultAddress"); }
        }

        /// <summary>
        /// список файлов для шаблонов вложения отдела обучения 
        /// </summary>
        public List<string> TrainingsAcceptanceFileNames
        {
            get
            {
                var result = new List<string>();
                var configurationsCol = new ConfigurationsCollection();
                string[] fileList;
                try
                {
                    fileList = Directory.GetFiles(configurationsCol.TrainingsDocsTemplatesPath);
                }
                catch (Exception)
                {
                    return result;
                }

                foreach (string str in fileList)
                {
                    string name = str.Split('\\').Last();
                    if (string.IsNullOrEmpty(name)) continue;
                    if (((name.Trim()).ToUpper()).Contains("ACCEPTANCE"))
                    {
                        result.Add(name);
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// путь к папке документов обучения
        /// </summary>
        public string TrainingsDocsPath
        {
            get
            {
                string result = GetValueByName("TrainingsDocumentsPath");
                if (CurrentDatabase.ToUpper() == "CRMT")
                    result = GetValueByName("TrainingsDocumentsPathTest");
                if (!string.IsNullOrEmpty(result))
                    return result;
                return "";
            }
        }

        /// <summary>
        /// Путь к темповой директории для техников
        /// </summary>
        public string TrainingsDocsTempPath
        {
            get
            {
                if (!string.IsNullOrEmpty(TrainingsDocsPath))
                {
                    return TrainingsDocsPath + "\\Temp";
                }
                return "";
            }
        }

        /// <summary>
        /// пусть директории шаблонов документов обучения
        /// </summary>
        public string TrainingsDocsTemplatesPath
        {
            get
            {
                if (!string.IsNullOrEmpty(TrainingsDocsPath))
                {
                    return TrainingsDocsPath + "\\Templates";
                }
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string TrainingsDocsTargetPath
        {
            get
            {
                if (!string.IsNullOrEmpty(TrainingsDocsPath))
                {
                    return TrainingsDocsPath + "\\Target";
                }
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string TrainingsAcceptenceMoscowFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\acceptenceMoscow.doc"; }
        }

        /// <summary>
        /// Шаблон - newRequest.doc
        /// </summary>
        public string TrainingsNewRequestFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\newRequest.doc"; }
        }

        ///// <summary>
        ///// 
        ///// </summary>
        //public string TrainingsRefuseFilePath
        //{
        //    get { return TrainingsDocsTemplatesPath + "\\refuse.doc"; }
        //}

        /// <summary>
        /// confirmation_remote.doc
        /// </summary>
        public string TrainingsConfirmationRemoteFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\confirmation_remote.doc"; }
        }

        /// <summary>
        /// confirmation_planned.doc
        /// </summary>
        public string TrainingsConfirmationPlannedFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\confirmation_planned.doc"; }
        }

        /// <summary>
        /// acceptance_remote.doc
        /// </summary>
        public string TrainingsAcceptanceRemoteFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\acceptance_remote.doc"; }
        }

        /// <summary>
        /// refuse_planned.doc
        /// </summary>
        public string TrainingsRefusePlannedFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\refuse_planned.doc"; }
        }

        /// <summary>
        /// refuse_remote.doc
        /// </summary>
        public string TrainingsRefuseRemoteFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\refuse_remote.doc"; }
        }

        /// <summary>
        /// Шаблон - coffee_brake_service.docx
        /// </summary>
        public string TrainingsCoffeeBrakeServiceFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\coffee_brake_service.docx"; }
        }

        /// <summary>
        /// Шаблон - registration_form.docx
        /// </summary>
        public string TrainingsRegistrationFormFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\registration_form.docx"; }
        }

        /// <summary>
        /// Шаблон - members_list.docx
        /// </summary>
        public string TrainingsMembersListFilePath
        {
            get { return TrainingsDocsTemplatesPath + "\\members_list.docx"; }
        }

        #endregion

        #region Technics

        /// <summary>
        /// 
        /// </summary>
        public string TechnicDocsPath
        {
            get
            {
                string result = GetValueByName("TechnicDocumentsPath");
                if (CurrentDatabase.ToUpper() == "CRMT")
                    result = GetValueByName("TechnicDocumentsPathTest");
                if (!string.IsNullOrEmpty(result))
                    return result;
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string TechnicAttachmentsPath
        {
            get { return TechnicDocsPath + "\\Attachments"; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string TechnicDocsTemplatesPath
        {
            get { return TechnicDocsPath + "\\Templates"; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string TechnicDocsReportsPath
        {
            get { return TechnicDocsPath + "\\Reports"; }
        }

        #endregion

        #region Turnovers

        /// <summary>
        /// полный путь к сохраняемым XLS файлам с оборотами для загрузки 
        /// </summary>
        public string TurnoversFilesUploadPath
        {
            get
            {
                string directoryName = GetValueByName("TurnoversFilesUploadDirectory");
                if (!string.IsNullOrEmpty(directoryName))
                    return AppDomain.CurrentDomain.BaseDirectory + "UploadedTurnovers";
                return AppDomain.CurrentDomain.BaseDirectory + "\\" + directoryName;
            }
        }

        #endregion

        #region Contracts

        /// <summary>
        /// Путь к шаблонам договоров
        /// </summary>
        public string ContractsTemplatePath
        {
            get { return GetValueByName("ContractsTemplatePath"); }
        }


        /// <summary>
        /// Путь к договорам
        /// </summary>
        public string ContractsPath
        {
            get { return GetValueByName("ContractsPath"); }
        }


        /// <summary>
        /// Путь к договорам
        /// </summary>
        public string ContractsScanPath
        {
            get { return GetValueByName("ContractsScansPath"); }
        }

        #endregion

        #endregion

        #region Extended public methods

        #region Trainings

        /// <summary>
        /// 
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public string GetTrainingsAcceptanceFilePathByRequestId(int idRequest)
        {
            var requestsCol = new TrainingsRequestsCollection();
            var request = (TrainingsRequests) requestsCol.GetItemById(idRequest);
            if (request != null)
            {
                if (request.TrainingsSchedules != null)
                    if (request.TrainingsSchedules.TrainingsPlaces != null)
                        if (request.TrainingsSchedules.TrainingsPlaces.AcceptanceFileName != null)
                            return TrainingsDocsTemplatesPath + "\\" +
                                   request.TrainingsSchedules.TrainingsPlaces.AcceptanceFileName;
            }
            return TrainingsDocsTemplatesPath + "\\acceptance.doc";
        }

        #endregion

        #endregion
    }
}